//
//  KWNLoginViewController.m
//  KWNClient
//
//  Created by 张明磊 on 14/10/17.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLLoginViewController.h"
#import "KWNNetwork.h"
#import "Model_question.h"
#import "Model_user.h"
#import "MLBlackTransition.h"
//#import "KWNQuestionFinishViewController.h"
#import "KWLFindMMViewController.h"
#import "MINavigationController.h"
//#import "KWNRegisterViewController.h"
#import "SPJoinInViewController.h"

NSString *const Notification_KWNFromRegist = @"Notification_KWNFromRegist";
NSString *const Notification_KWNFromFromList = @"Notification_KWNFromFromList";
NSString *const Notification_KWNFromFeedback = @"Notification_KWNFromFeedback";
//任意界面token失效
NSString *const Notification_KWNLoginOut = @"Notification_KWNLoginOut";

NSString *const Notification_KWNIos6ReloadHome = @"Notification_KWNIos6ReloadHome";

typedef NS_ENUM(NSInteger, KWNRegistButtonTag){
    KWNLoginButtonTag_back          = 0,
    KWNLoginButtonTag_wangji             ,
    KWNLoginButtonTag_denglu            ,
    KWNLoginButtonTag_xianshi            ,
    KWNLoginButtonTag_regist              ,
};

@interface KWLLoginViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *textField_phone;
@property (strong, nonatomic) UITextField *textField_mm;

@property (assign, nonatomic) NSInteger int_loginTag;
@property (strong, nonatomic) UIView *imageView_title;
@property (strong, nonatomic) UIImageView *imageview_top;
@property (strong, nonatomic) UIView *view_phone;
@property (strong, nonatomic) UIView *view_MM;
@property (strong, nonatomic) UIButton *button_mima;
@property (strong, nonatomic) UIButton *button_send;
@property (strong, nonatomic) UIButton *button_xieyi;
@property (strong, nonatomic) UIButton *button_jiameng;

@end

@implementation KWLLoginViewController

#pragma mark - 不同情况调用登陆 -
/**
 *   loginTag
 0 - 注册页面进入
 1 - 登出后进入
 2 - 问题列表页面进入
 3 - 反馈
 4 - 从侧拉进入
 5 - 律师登陆
 */
- (id)initWithTag:(NSInteger)loginTag{
    self = [super init];
    if(self){
        _int_loginTag = loginTag;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self UI_login];
    
    if(IOS7_VERSION){
        [self.navigationController enabledMLBlackTransition:NO];
    }
    else{
        [self.navigationController_MI setCanDragBack:NO];
    }
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LoginPage"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LoginPage"];
}

- (void)dealloc{
    if(IOS7_VERSION){
        [self.navigationController enabledMLBlackTransition:YES];
    }
    else{
        [self.navigationController_MI setCanDragBack:YES];
    }
}

- (void)UI_login{
    
    _imageView_title = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44 + IOS7_SIZE)];
    _imageView_title.backgroundColor = RGB(91, 165, 229);
    _imageView_title.tag = TagOfView;
    
    UILabel *label_title = [[UILabel alloc] initWithFrame:CGRectMake(_imageView_title.frame.origin.x,IOS7_SIZE + 5,_imageView_title.frame.size.width,35)];
    label_title.backgroundColor = [UIColor clearColor];
    label_title.textColor = ColorOfTitle;
    label_title.textAlignment = NSTextAlignmentCenter;
    label_title.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.0f];
    label_title.text = @"欢迎您!";
    
    _imageview_top = [[UIImageView alloc] initWithFrame:CGRectMake((MainScreenWidth - 143)/2, _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (100 -50)/2, 143, 50)];
    _imageview_top.image = [UIImage imageFileName:@"login_top.png"];
    _imageview_top.tag = TagOfView + 1;
    [self.view addSubview:_imageview_top];
    
    _view_phone = [[UIView alloc] initWithFrame:CGRectMake(10, label_title.frame.origin.y + label_title.frame.size.height + 100, 300, 46)];
    _view_phone.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_view_phone];
    //设置矩形四个圆角半径
    _view_phone.layer.cornerRadius = 5.0;
    _view_phone.layer.borderWidth = 1.0;//边框宽度
    _view_phone.layer.borderColor = RGB(198, 198, 198).CGColor;//边框颜色
    
    _textField_phone = [[UITextField alloc] initWithFrame:CGRectMake(30, _view_phone.frame.origin.y, 260, 46)];
    _textField_phone.backgroundColor = [UIColor clearColor];
    _textField_phone.textColor = [UIColor blackColor];
    _textField_phone.textAlignment = NSTextAlignmentLeft;
    NSString *string_phone = [[Model_user sharedInstance] getUserPhone];
    if(string_phone){
        _textField_phone.text = string_phone;
    }
    else{
        _textField_phone.placeholder = @"请输入手机号";
    }
    _textField_phone.font = [UIFont systemFontOfSize:15];
    _textField_phone.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField_phone.clearButtonMode = UITextFieldViewModeAlways;
    _textField_phone.keyboardType = UIKeyboardTypeNumberPad;
    //去掉首字母大写和自动纠错
    _textField_phone.autocorrectionType = UITextAutocorrectionTypeNo;
    _textField_phone.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //textField_phone.delegate = self;
    //字多自动缩进
    _textField_phone.adjustsFontSizeToFitWidth = YES;
    //缩进最小字体
    _textField_phone.minimumFontSize = 20;
    [self.view addSubview:_textField_phone];
//    [textField_phone becomeFirstResponder];
    _textField_phone.tag = 100;
    
    _view_MM = [[UIView alloc] initWithFrame:CGRectMake(10, _view_phone.frame.origin.y + _view_phone.frame.size.height + 10, 300, 46)];
    _view_MM.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_view_MM];
    //设置矩形四个圆角半径
    _view_MM.layer.cornerRadius = 5.0;
    _view_MM.layer.borderWidth = 1.0;//边框宽度
    _view_MM.layer.borderColor = RGB(198, 198, 198).CGColor;//边框颜色
    
    _textField_mm = [[UITextField alloc] initWithFrame:CGRectMake(30, _view_MM.frame.origin.y, 260, 46)];
    _textField_mm.backgroundColor = [UIColor clearColor];
    _textField_mm.textColor = [UIColor blackColor];
    _textField_mm.textAlignment = NSTextAlignmentLeft;
    _textField_mm.placeholder = @"请输入密码";
    _textField_mm.font = [UIFont systemFontOfSize:15];
    _textField_mm.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField_mm.clearButtonMode = UITextFieldViewModeAlways;
    _textField_mm.keyboardType = UIKeyboardTypeEmailAddress;
    //去掉首字母大写和自动纠错
    _textField_mm.secureTextEntry = YES;
    _textField_mm.autocorrectionType = UITextAutocorrectionTypeNo;
    _textField_mm.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField_mm.delegate = self;
    //字多自动缩进
    _textField_mm.adjustsFontSizeToFitWidth = YES;
    //缩进最小字体
    _textField_mm.minimumFontSize = 20;
    [self.view addSubview:_textField_mm];
    
    UIButton *button_closeKey = [UIButton buttonWithType:UIButtonTypeCustom];
    button_closeKey.frame = CGRectMake(0, 0, 320, 30);
    [button_closeKey setImage:[UIImage imageFileName:@"button_closeKey.png"] forState:UIControlStateNormal];
    [button_closeKey addTarget:self action:@selector(clickBtn_closeKeybored)forControlEvents:UIControlEventTouchUpInside];
    [_textField_mm setInputAccessoryView:button_closeKey];
    [_textField_phone setInputAccessoryView:button_closeKey];

    button_closeKey.tag = 102;
    
    _button_mima = [UIButton buttonWithType:UIButtonTypeCustom];
    _button_mima.frame = CGRectMake(_textField_mm.frame.origin.x + _textField_mm.frame.size.width - 60, _textField_mm.frame.origin.y + 5, 62, 35);
    [_button_mima setImage:[UIImage imageFileName:@"button_showM.png"] forState:UIControlStateNormal];
    [_button_mima setImage:[UIImage imageFileName:@"button_showM_s.png"] forState:UIControlStateSelected];
    [_button_mima addTarget:self action:@selector(didClickButton_login:)forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button_mima];
    _button_mima.tag = KWNLoginButtonTag_xianshi;
    
    _button_send = [UIButton buttonWithType:UIButtonTypeCustom];
    _button_send.frame = CGRectMake(_view_MM.frame.origin.x, _view_MM.frame.origin.y + _view_MM.frame.size.height + 10, _view_MM.frame.size.width, _view_MM.frame.size.height);
    _button_send.backgroundColor = RGB(91, 165, 229);
    [_button_send setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button_send setTitle:@"登录" forState:UIControlStateNormal];
    _button_send.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    [_button_send addTarget:self action:@selector(didClickButton_login:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button_send];
    _button_send.tag = KWNLoginButtonTag_denglu;
    _button_send.layer.cornerRadius = 5.0;
    
    _button_xieyi = [UIButton buttonWithType:UIButtonTypeCustom];
    _button_xieyi.frame = CGRectMake(self.view.frame.size.width/2 + 20, _button_send.frame.origin.y + _button_send.frame.size.height, 130, 30);
    _button_xieyi.backgroundColor = [UIColor clearColor];
    [_button_xieyi setTitleColor:RGB(0, 162, 232) forState:UIControlStateNormal];
    [_button_xieyi setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [_button_xieyi addTarget:self action:@selector(didClickButton_login:) forControlEvents:UIControlEventTouchUpInside];
    _button_xieyi.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [self.view addSubview:_button_xieyi];
    _button_xieyi.tag = KWNLoginButtonTag_wangji;
    
    
    _button_jiameng = [UIButton buttonWithType:UIButtonTypeCustom];
    _button_jiameng.frame = CGRectMake(_button_send.frame.origin.x, ViewHeight - 20 - _button_send.frame.size.height,_button_send.frame.size.width, _button_send.frame.size.height);
    _button_jiameng.layer.cornerRadius = 5.0;
    _button_jiameng.backgroundColor = RGB(134, 207, 80);
    [_button_jiameng setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button_jiameng setTitle:@"还没加盟？点我立即入驻" forState:UIControlStateNormal];
//    [_button_jiameng setBackgroundImage:[UIImage imageFileName:@"login_bottom.png"] forState:UIControlStateNormal];
    _button_jiameng.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    [_button_jiameng addTarget:self action:@selector(clickBtn_jiameng:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button_jiameng];

    
//    UIImageView *imageview_bottom = [[UIImageView alloc] initWithFrame:CGRectMake((MainScreenWidth - 291)/2, ViewHeight - 20 - 102, 291, 102)];
//    if (IOS6_VERSION) {
//        imageview_bottom.frame = CGRectMake((MainScreenWidth - 291)/2, ViewHeight - 10 - 102, 291, 102);
//    }
//    imageview_bottom.image = [UIImage imageFileName:@"login_bottom.png"];
//    [self.view addSubview:imageview_bottom];
    
    [self.view addSubview:_imageView_title];
    [self.view addSubview:label_title];
}

- (void)clickBtn_closeKeybored
{
    [self.view endEditing:YES];
}

- (void)clickBtn_jiameng:(id)sender
{
    SPJoinInViewController *control = [[SPJoinInViewController alloc] init];
    [self pushViewController:control];

}

- (void)didClickButton_login:(UIButton *)button{
    switch (button.tag) {
        case KWNLoginButtonTag_back:{
            [self.view endEditing:YES];
            switch (_int_loginTag) {
                case 0:{
                    [self popViewController];
                }break;
                case 1:{
                    [self popViewController];
                }break;
                case 2:{
                    [self popViewController];
                }break;
                case 3:{
                    [self popViewController];
                }break;
                case 4:{
                    [self popViewController];
                }break;
                default:
                    break;
            }
        }break;
        case KWNLoginButtonTag_wangji:{
            [MobClick event:@"wangjimima"];
            KWLFindMMViewController *controller_find = [[KWLFindMMViewController alloc] init];
            [self pushViewController:controller_find];
        }break;
        case KWNLoginButtonTag_denglu:{
            [MobClick event:@"denglu"];
            if(_textField_mm.text.length == 0 || _textField_phone.text == 0){
                [SVProgressHUD showErrorWithStatus:@"电话和密码不能为空" duration:1.5];
            }
            else if([UIUtils validateMobile:_textField_phone.text]){
                [SVProgressHUD showWithStatus:@"登录中..." maskType:SVProgressHUDMaskTypeClear];
                [Model_question sharedInstance].string_phone = _textField_phone.text;
                [[KWNNetwork sharedInstance] login_intPassword:_textField_mm.text finishBlock:^(NSInteger stateCode, NSMutableArray *result) {
                    switch (stateCode) {
                        case 10000:{
                            NSString *string_msg  = result[0];
                            [SVProgressHUD dismissWithSuccess:string_msg afterDelay:1.5];
                            [self.view endEditing:YES];
                            
                            NSString *string_id = result[1];
                            NSString *string_token = result[2];
                            [[Model_user sharedInstance] setUID:string_id];
                            [[Model_user sharedInstance] setToken:string_token];
                            [Model_question sharedInstance].string_token = string_token;
                            [[Model_user sharedInstance] setUserPhone:[Model_question sharedInstance].string_phone];
                            
                            double delayInSeconds = 1.5;
                            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                                switch (_int_loginTag) {
                                    case 0:{
                                    }break;
                                    case 1:{
                                        [self popViewController];
                                    }break;
                                    case 2:{
                                        /*[self popViewController];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_KWNFromFromList object:nil];*/
                                    }break;
                                    case 3:{
                                        [self popViewController];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_KWNFromFeedback object:nil];
                                    }break;
                                    case 4:{
                                        [self popViewController];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_KWNIos6ReloadHome object:nil];
                                    }break;
                                    case 5:{
                                        [self.navigationController enabledMLBlackTransition:YES];
                                        [self.navigationController popToRootViewControllerAnimated:NO];
                                    }break;
                                    case 6:{
                                        [self.navigationController enabledMLBlackTransition:YES];
                                        [Model_user sharedInstance].bool_isLoadLawyer = YES;
                                        
                                        if(IOS6_VERSION){
                                            [self.navigationController_MI popToRootViewControllerAnimated:YES];
                                        }
                                        else{
                                            [self.navigationController popToRootViewControllerAnimated:YES];
                                        }
                                        double delayInSeconds = 1.5;
                                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                                        dispatch_after(popTime, dispatch_get_main_queue(), ^{
                                            [[NSNotificationCenter defaultCenter] postNotificationName:@"notificaition_KWLReloadHomeAndIsWebLog" object:nil];
                                        });
                                    }break;
                                    default:
                                        break;
                                }
                            });
                        }break;
                        default:{
                            NSString *string_msg  = result[0];
                            [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
                        }break;
                    }
                }];
            }
            else{
                [SVProgressHUD showErrorWithStatus:@"电话号码非法" duration:1.5];
            }
        }break;
        case KWNLoginButtonTag_xianshi:{
            [MobClick event:@"xianshimima"];
            button.selected =! button.selected;
            if(IOS7_VERSION){
                _textField_mm.secureTextEntry =! _textField_mm.secureTextEntry;
                NSString *string_mm = _textField_mm.text;
                _textField_mm.text = nil;
                _textField_mm.text = string_mm;
            }
            else{
                _textField_mm.enabled = false;
                _textField_mm.secureTextEntry =! _textField_mm.secureTextEntry;
                _textField_mm.enabled = true;
            }
        }break;
        case KWNLoginButtonTag_regist:{
            //KWNRegisterViewController *controller_regist = [[KWNRegisterViewController alloc] initWithTag:1];
            //[self pushViewController:controller_regist];
        }break;
        default:
            break;
    }
}

- (void)loginSubViewsFrameUp
{
    [UIView animateWithDuration:0.3 animations:^{
        [_imageview_top setFrameTop:_imageview_top.frame.origin.y - 30];
        [_view_phone setFrameTop:_view_phone.frame.origin.y - 30];
        [_textField_phone setFrameTop:_textField_phone.frame.origin.y - 30];
        [_view_MM setFrameTop:_view_MM.frame.origin.y - 30];
        [_textField_mm setFrameTop:_textField_mm.frame.origin.y - 30];
        [_button_mima setFrameTop:_button_mima.frame.origin.y - 30];
    }];
}

- (void)loginSubViewsFrameRestore
{
    [UIView animateWithDuration:0.3 animations:^{
        [_imageview_top setFrameTop:_imageview_top.frame.origin.y + 30];
        [_view_phone setFrameTop:_view_phone.frame.origin.y + 30];
        [_textField_phone setFrameTop:_textField_phone.frame.origin.y + 30];
        [_view_MM setFrameTop:_view_MM.frame.origin.y + 30];
        [_textField_mm setFrameTop:_textField_mm.frame.origin.y + 30];
        [_button_mima setFrameTop:_button_mima.frame.origin.y + 30];
    }];
}
#pragma mark - 输入回调 -
/**
 *  输入回调
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if(textField.tag == 100){
        if([string isEqualToString:@""]){
            return YES;
        }
        else if(textField.text.length == 11){
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _textField_mm) {
        
        NSString *device = [UIUtils currentDevicePlatformString];
        if ([device isEqualToString:@"iPhone 4S"]||[device isEqualToString:@"iPhone 4"]||[device isEqualToString:@"Verizon iPhone 4"]) {
            if (_imageview_top.frame.origin.y >= _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (100 -50)/2) {
                [self loginSubViewsFrameUp];
            }
        }
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *device = [UIUtils currentDevicePlatformString];
    if ([device isEqualToString:@"iPhone 4S"]||[device isEqualToString:@"iPhone 4"]||[device isEqualToString:@"Verizon iPhone 4"]) {
        if (_imageview_top.frame.origin.y < _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (100 -50)/2) {
            [self loginSubViewsFrameRestore];
        }
    }
}

@end
